import Toast from 'tdesign-miniprogram/toast/index';
import { login, getUnit, getPersonalByUserNumber } from '../../utils/request/login/loginReq';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    unitPickerVisible: false,
    userNumberError: false,
    passwordError: false,
    trueCodeError: false,
    yanzhen: '',
    true_code: '',
    yanzhen_arr: [],
    style: 'border: 2rpx solid rgba(220,220,220,1);border-radius: 12rpx;',
    loginForm: {
      userNumber: '',
      password: '',
      unitId: null,
      unitName: '',
      authCode: ''
    },
    unitName: [    ]
  },
  getUnitList(){

      getUnit().then(res => {
        let unitId = res.data.unitId
        let arr = []
        for(let i = 0; i < unitId.length; i++){
          let form = {
            label: res.data.unitName[i],
            value: unitId[i]
          }
          arr.push(form)
        }
        this.setData({
          unitName: arr
        })
      })

  },
  login() {
     // 密码 用户名 验证码格式都正确
    if(!this.data.passwordError && !this.data.userNumberError && !this.data.trueCodeError){
      login(this.data.loginForm).then(res => {
        if(res.data.code === 200){
          wx.setStorageSync('roleId', res.data.data.roleId)
          wx.setStorageSync('userNumber', res.data.data.userNumber)
          wx.setStorageSync('unitId', res.data.data.unitId)
          console.log(res.data)
          this.setPersonBaseInfo()
          Toast({
            context: this,
            selector: '#t-toast',
            message: '登录成功',
            icon: 'check-circle',
            direction: 'column',
          });
          setTimeout(() => {
            wx.switchTab({
              url: '../index/index',
            })
          }, 3000)
        }else {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '账号或密码错误',
            icon: 'check-circle',
            direction: 'column',
          });
          return 
        }
      })
    }else {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请输入正确信息',
        icon: 'close',
        direction: 'column',
      });
      return 
    }
  },
  setPersonBaseInfo(){
    getPersonalByUserNumber().then(resp => {
        wx.setStorageSync('departmentId', resp.data.departmentId)
    })
  },


  onUnitPicker() {
    this.setData({
      unitPickerVisible: true
    })
  },
  onUnitPickerChange(e) {
    const {
      key
    } = e.currentTarget.dataset;
    const {
      value
    } = e.detail;
    this.setData({
      loginForm: {
        unitName: e.detail.label[0],
        unitId: e.detail.value[0]
      }
    })
  },
  onUnitPickerCancel() {
    this.setData({
      unitPickerVisible: false
    })
  },
  handleCanvas() {
    this.drawAuthCode(this.data.yanzhen_arr)
  },
  // 渲染出验证码
  drawAuthCode(show_num) {
    const canvas = wx.createCanvasContext('canvas') // 获取到canvas上下文
    const canvasWidth = canvas.width
    const canvasHeight = canvas.height


    const sCode =
      'a,b,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0'
    const aCode = sCode.split(',')
    const aLength = aCode.length // 获取到数组的长度

    // 4个验证码数
    for (let i = 0; i <= 3; i++) {
      const j = Math.floor(Math.random() * aLength) // 获取到随机的索引值
      const deg = (Math.random() * 30 * Math.PI) / 180 // 产生0~30之间的随机弧度
      const txt = aCode[j] // 得到随机的一个内容
      show_num[i] = txt.toLowerCase() // 依次把取得的内容放到数组里面
      const x = 10 + i * 20 // 文字在canvas上的x坐标
      const y = 20 + Math.random() * 8 // 文字在canvas上的y坐标

      canvas.setFontSize(23)
      canvas.setFillStyle(this.randomColor())
      canvas.translate(x, y)
      canvas.rotate(deg)
      canvas.fillText(txt, 0, 0)
      canvas.rotate(-deg)
      canvas.translate(-x, -y)
    }

    // 验证码上显示6条线条
    for (let i = 0; i <= 5; i++) {
      canvas.setStrokeStyle(this.randomColor())
      canvas.beginPath()
      canvas.moveTo(Math.random() * canvasWidth, Math.random() * canvasHeight)
      canvas.lineTo(Math.random() * canvasWidth, Math.random() * canvasHeight)
      canvas.stroke()
    }

    // 验证码上显示31个小点
    for (let i = 0; i <= 30; i++) {
      canvas.setStrokeStyle(this.randomColor())
      canvas.beginPath()
      const x = Math.random() * canvasWidth
      const y = Math.random() * canvasHeight
      canvas.moveTo(x, y)
      canvas.lineTo(x + 1, y + 1)
      canvas.stroke()
    }

    canvas.draw(false, () => {
      // 将生成的验证码保存到show_num中
      const num = show_num.join('')
      this.true_code = num
    })
  },
  // 登录账号格式验证  
  handleUserNumberInput(event) {
    const value = event.detail.value
    if (/^[^\s]{4,12}$/.test(value)) {
      this.setData({
        'loginForm.userNumber': value,
        userNumberError: false
      })
    } else {
      this.setData({
        userNumberError: true
      })
    }
  },
  // 密码格式验证
  handlePasswordInput(event) {
    const value = event.detail.value
    if (/^[^\s]{8,16}$/.test(value)) {
      this.setData({
        'loginForm.password': value,
        passwordError: false
      })
    } else {
      this.setData({
        passwordError: true
      })
    }
  },
  // 验证码格式验证
  handleTrueCodeInput(event){
    const value = event.detail.value
    if(this.true_code === value){
      this.setData({
        trueCodeError: false
      })
    }else {
      this.setData({
        trueCodeError: true
      })
    }
  },
  // 生成随机颜色的函数
  randomColor() {
    const color = '#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0')
    return color
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getUnitList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.handleCanvas()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})